package com.jackrain.nea.fc.dl.mapper;


import com.alibaba.fastjson.JSONObject;
import com.jackrain.nea.fc.utils.ObjectToUtil;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author kangcong
 * @date 2018/08/07
 **/
@Mapper
public interface ViewDLTranWeightInfoMapper {

    //查询单据和序号是否已存在
    @Select("SELECT COUNT(1) FROM DL_T_TRAN_WEIGHT_INFO WHERE BILL_NO=#{billno} AND LINE_NO=#{lineno}")
    int selectBillLineCount(@Param("billno") String billno,
                            @Param("lineno") String lineno);

    @Insert("INSERT INTO DL_T_TRAN_WEIGHT_INFO(BILL_TYPE, BILL_NO, LINE_NO, BILL_LINE, WEIGHT, CREATETIME) values(#{billtype}, #{billno}, #{lineno}, #{billline}, #{weight}, #{createtime})")
    int insertTranWeight(@Param("billtype") String billtype,
                         @Param("billno") String billno,
                         @Param("lineno") String lineno,
                         @Param("billline") String billline,
                         @Param("weight") double weight,
                         @Param("createtime") String createtime);

    @Update("UPDATE DL_T_TRAN_WEIGHT_INFO SET WEIGHT=#{weight}, MODIFIEDDATE=#{updatetime} where BILL_NO=#{billno} and LINE_NO=#{lineno}")
    int updateTranWeight(@Param("billno") String billno,
                         @Param("lineno") String lineno,
                         @Param("weight") double weight,
                         @Param("updatetime") String updatetime);

    @Select("SELECT DISTINCT A.ID AS ID FROM DL_B_TRAN A WHERE A.BILL_NO = #{billno}")
    Long selectTranBillId(@Param("billno") String billno);

    @InsertProvider(type = ViewDlWeight.class, method = "insertSql")
    int insert(@Param("tableName") String tableName, @Param("insertKeys") JSONObject insertKeys);

    @Select("SELECT ID,CP_C_ORIG_ID,CP_C_DEST_ID FROM DL_B_TRAN WHERE BILL_NO =#{billno}")
    HashMap selectStoreIdByBillno(@Param("billno") String billno);

    class ViewDlWeight {
        public String insertSql(Map<String, Object> para) {
            String tableName = ObjectToUtil.getString(para.get("tableName"), "");
            JSONObject insertKeys = (JSONObject) para.get("insertKeys");

            String sql = new SQL() {
                {
                    Set<String> keySet = insertKeys.keySet();
                    INSERT_INTO(tableName);
                    for (int i = 0; i < insertKeys.size(); i++) {
                        String key = (String) keySet.toArray()[i];
                        if (insertKeys.getString(key) == null) {
                            continue;
                        }
                        VALUES(key, "#{insertKeys." + key + "}");
                    }
                }
            }.toString();

            System.out.print("sql ========  >" + sql + "\r\n");

            return sql;
        }
    }
}
